package com.duofan.gmall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.duofan.gmall.auth.config.OAuth2Properties;
import com.duofan.gmall.auth.feign.MemberFeignService;
import com.duofan.gmall.auth.vo.SocialUser;
import com.duofan.gmall.common.constant.CommonConstant;
import com.duofan.gmall.common.utils.HttpUtils;
import com.duofan.gmall.common.utils.R;
import com.duofan.gmall.common.vo.MemberRespVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 社交登录
 */
@Slf4j
@Controller
public class OAuth2Controller {
    @Autowired
    MemberFeignService memberFeignService;
    @Autowired
    OAuth2Properties oauth2Properties;

    @GetMapping("/oauth2/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session, HttpServletResponse servletResponse) throws Exception {
        // 根据code获取access token
        Map<String, String> map = new HashMap<>();
        map.put("client_id", oauth2Properties.getClientId());
        map.put("client_secret", oauth2Properties.getClientSecret());
        map.put("redirect_uri", oauth2Properties.getRedirectUri());
        map.put("grant_type", oauth2Properties.getGrantType());
        map.put("code", code);

        Map<String, String> headers = new HashMap<>();
        Map<String, String> querys = new HashMap<>();

        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", headers, querys, map);
        if(response.getStatusLine().getStatusCode() == 200) {
            // 成功
            String json = EntityUtils.toString(response.getEntity());
            SocialUser userVo = JSON.parseObject(json, SocialUser.class);
            // 当前登录用户第一次登录自动注册
            R r = memberFeignService.oauth2Login(userVo);
            if(r.getCode() == 0) {
                MemberRespVo data = r.getData(new TypeReference<MemberRespVo>() {});
                log.info(JSON.toJSONString(data, true));
                // TODO 使用JSON序列化方式保存到redis
                session.setAttribute("loginUser", data);
                // 登录成功跳回首页
                return CommonConstant.REDIRECT_HOME;
            } else {
                return CommonConstant.REDIRECT_AUTH + "/login.html";
            }
        } else {
            return CommonConstant.REDIRECT_AUTH +  "/login.html";
        }
    }
}
